<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select
        v-model="listQuery.agencyId"
        filterable
        clearable
        :filter-method="dataFilter"
        placeholder="机构选择"
        style="width: 300px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      >
        <el-option
          v-for="item in options"
          :key="item.agencyId"
          :label="item.agencyName"
          :value="item.agencyId"
        />
      </el-select>
      <el-select
        v-model="listQuery.type"
        clearable
        placeholder="选择机构类型"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      >
        <el-option value="CRM" label="广告">广告</el-option>
        <el-option value="API" label="保险">保险</el-option>
      </el-select>
      <div class="ec-input-range">
        <el-input
          v-model="listQuery.minCoin"
          style="width: 100px;"
          placeholder="最低曝光"
          @input="listQuery.minCoin = listQuery.minCoin.replace(/[^\d]/g, ' ')"
          @blur="handleVal"
        ></el-input>
        <div class="ec-input-range-divider"></div>
        <el-input
          v-model="listQuery.maxCoin"
          style="width: 100px;"
          @input="listQuery.maxCoin = listQuery.maxCoin.replace(/[^\d]/g, ' ')"
          @blur="handleVal"
          placeholder="最高曝光"
        ></el-input>
      </div>
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
        :loading="filterLoading"
      >
        搜索
      </el-button>
    </div>
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      element-loading-text="加载中"
      :data="tableData"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="机构ID" width="150" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.agencyId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="机构名称" class-name="status-col" min-width="110">
        <template slot-scope="{ row }">
          {{ row.agencyName }}
        </template>
      </el-table-column>
      <el-table-column label="机构类型" width="150" align="center">
        <template slot-scope="{ row }">
          <span>{{ agencyIdText[row.accType] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="剩余曝光" align="center" width="150">
        <template slot-scope="{ row }">
          <span>{{ row.coin }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" width="180">
        <template slot-scope="{ row }">
          <span>{{ row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注详情" align="center" width="180">
        <template slot-scope="{ row }">
          <el-button type="text" @click="queryDetail(row.agencyId)"
            >查看详情</el-button
          >
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        min-width="110"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row }">
          <el-button size="mini" type="primary" @click="handleView(row)">
            查看明细
          </el-button>
          <el-button size="mini" type="primary" @click="handleEdit(row)">
            调账
          </el-button>
          <el-button size="mini" type="primary" @click="handleRemark(row)">
            备注
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.current"
      :limit.sync="listQuery.size"
      @pagination="getListAcc"
    />
    <el-dialog
      width="50%"
      title="调账"
      :visible.sync="dialogFormVisible"
      append-to-body
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="reconciliation"
        label-position="left"
        label-width="90px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="曝光消耗" prop="coin">
          <el-input-number
            placeholder="请输入"
            class="filter-item"
            v-model="reconciliation.coin"
            :precision="2"
            :step="0.1"
            :min="0"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="消耗类型" prop="symbol">
          <el-select
            v-model="reconciliation.symbol"
            clearable
            placeholder="请选择消耗类型"
            style="width: 200px;"
            class="filter-item"
          >
            <el-option value="PLUS" label="增">增</el-option>
            <el-option value="SUB" label="减">减</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            type="textarea"
            placeholder="请输入内容"
            v-model="reconciliation.remark"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="auditCount()" :loading="btnLoading">
          确认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog title="曝光明细" :visible.sync="viewProtocolialog" width="70%">
      <div class="filter-container">
        <el-input
          v-model="listQuery1.trans"
          placeholder="曝光消耗"
          style="width: 150px;"
          class="filter-item"
        />
        <el-select
          v-model="listQuery1.symbol"
          clearable
          placeholder="消耗类型"
          style="width: 200px;"
          class="filter-item"
        >
          <el-option value="PLUS" label="增">增</el-option>
          <el-option value="SUB" label="减">减</el-option>
        </el-select>
        <el-date-picker
          v-model="times"
          class="filter-item"
          start-placeholder="消耗开始时间"
          end-placeholder="消耗结束时间"
          style="width: 400px;"
          type="datetimerange"
          value-format="yyyy-MM-dd HH:mm:ss"
        />
        <el-button
          v-waves
          class="filter-item"
          type="primary"
          icon="el-icon-search"
          @click="handleFilterDedail"
          :loading="detailLoading"
        >
          搜索
        </el-button>
      </div>
      <el-table
        :key="detailtableKey"
        v-loading="detailLoading"
        element-loading-text="加载中"
        :data="listDetail"
        border
        fit
        highlight-current-row
        style="width: 100%;"
      >
        <el-table-column label="机构ID" width="100" align="center">
          <template slot-scope="{ row }">
            <span>{{ row.agencyId }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="机构名称"
          class-name="status-col"
          min-width="110"
        >
          <template slot-scope="{ row }">
            {{ row.agencyName }}
          </template>
        </el-table-column>

        <el-table-column label="机构类型" width="150" align="center">
          <template slot-scope="{ row }">
            <span>{{ agencyIdText[row.accType] }}</span>
          </template>
        </el-table-column>
        <el-table-column label="消耗类型" align="center" width="150">
          <template slot-scope="{ row }">
            <span>{{ row.symbol == 'SUB' ? '减' : '增' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="曝光消耗" align="center" width="180">
          <template slot-scope="{ row }">
            <span>{{ row.transCoin }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" width="100" align="center">
          <template slot-scope="{ row }">
            <span>{{ row.remark }}</span>
          </template>
        </el-table-column>
        <el-table-column label="消耗时间" align="center" width="180">
          <template slot-scope="{ row }">
            <span>{{ row.transTime }}</span>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="detailTotal > 0"
        :total="detailTotal"
        :page.sync="listQuery1.current"
        :limit.sync="listQuery1.size"
        @pagination="getlistDetail"
      />
      <div class="listDetailTotal">曝光总消耗：{{ listDetailTotal }}</div>
    </el-dialog>
    <!-- 查看详情 -->
    <el-dialog
      title="备注记录"
      :visible.sync="detailDialogVisible"
      width="50%"
      :before-close="handleClose"
    >
      <el-table
        v-loading="loading"
        :data="exposureRemarkDetail"
        style="width: 100%"
        :row-class-name="tableRowClassName"
      >
        <el-table-column prop="createTime" label="日期" width="180">
        </el-table-column>
        <el-table-column prop="operator" label="角色" width="180">
        </el-table-column>
        <el-table-column prop="detail" label="备注"> </el-table-column>
      </el-table>
      <el-pagination
        style="marginTop:40px"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage4"
        :page-sizes="[5, 10, 20, 30]"
        :page-size="5"
        layout="total, sizes, prev, pager, next, jumper"
        :total="exposureRemarkTotal"
      >
      </el-pagination>
    </el-dialog>
    <!-- 查看详情 -->
    <el-dialog
      title="备注记录"
      :visible.sync="detailDialogVisible"
      width="50%"
      :before-close="handleClose"
    >
      <el-table
        :data="exposureRemarkDetail"
        style="width: 100%"
        :row-class-name="tableRowClassName"
      >
        <el-table-column prop="createTime" label="日期" width="180">
        </el-table-column>
        <el-table-column prop="operator" label="角色" width="180">
        </el-table-column>
        <el-table-column prop="detail" label="备注"> </el-table-column>
      </el-table>
      <el-pagination
        style="marginTop:40px"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage4"
        :page-sizes="[5, 10, 20, 30]"
        :page-size="5"
        layout="total, sizes, prev, pager, next, jumper"
        :total="exposureRemarkTotal"
      >
      </el-pagination>
    </el-dialog>
  </div>
</template>
<script>
import {
  getListAcc,
  getlistDetail,
  updateCount,
  getAgency,
  getListDetailTotal,
  getDetailByAgencyId,
  addDetailRemark
} from '@/api/account.js';
import Pagination from '@/components/Pagination'; // secondary package based on el-pagination

export default {
  name: 'AccountExposure',
  components: { Pagination },
  data() {
    return {
      agencyIdText: {
        CRM: '广告',
        API: '保险'
      },
      // 账户列表
      tableData: [],
      total: 0,
      tableKey: 0,
      listQuery: {
        current: 1,
        size: 10,
        agencyId: '',
        type: '',
        minCoin: '',
        maxCoin: ''
      },
      // 明细
      listDetail: [],
      detailTotal: 0,
      detailtableKey: 0,
      listQuery1: {
        size: 10,
        current: 1,
        startTime: '',
        endTime: '',
        type: '',
        agencyId: '',
        symbol: '',
        trans: ''
      },
      listQuery2: {
        startTime: '',
        endTime: '',
        type: '',
        agencyId: ''
      },
      listDetailTotal: 0,
      timeNow: [
        new Date(new Date().toLocaleDateString()).getTime(),
        new Date(new Date().toLocaleDateString()).getTime() +
          (24 * 60 * 60 * 1000 - 1)
      ],
      times: '',
      reconciliation: {
        id: undefined,
        coin: '',
        symbol: '',
        remark: '',
        type: ''
      },
      dialogFormVisible: false,
      viewProtocolialog: false,
      rules: {
        symbol: [{ required: true, message: '请选择类型', trigger: 'blur' }],
        remark: [{ required: true, message: '请填写备注', trigger: 'blur' }],
        coin: [{ required: true, message: '请输入', trigger: 'blur' }]
      },
      minCoin: '',
      maxCoin: '',
      optionsCopy: [],
      options: [],
      listLoading: false,
      detailLoading: false,
      btnLoading: false,
      filterLoading: false,
      detailDialogVisible: false,
      // 备注详情分页参数
      exposureRemarkDetail: [],
      exposureRemarkTotal: '',
      remarkDetailPage: {
        size: 5,
        current: 1,
        agencyId: ''
      },
      loading: true,
      // 备注详情DTO
      exposureRemarkDTO: {}
    };
  },
  created() {
    this.getListAcc(this.listQuery);
    this.getAgency();
  },
  watch: {
    'dynamicValidateForm.domains': {
      handler(newArr) {
        // 一开始都设置为允许使用
        this.h5Arr = this.h5Arr.map(item => {
          item.disabled = false;
          return item;
        });
        // 将选过的设置为禁用
        newArr.forEach(x => {
          this.h5Arr.forEach(y => {
            if (x.value === y.value) {
              y.disabled = true;
            }
          });
        });
      },
      deep: true
    }
  },
  methods: {
    handleVal() {
      const _this = this;
      if (
        _this.listQuery.minCoin === '' ||
        _this.listQuery.minCoin === undefined ||
        _this.listQuery.minCoin === null ||
        _this.listQuery.maxCoin === '' ||
        _this.listQuery.maxCoin === undefined ||
        _this.listQuery.maxCoin === null
      ) {
        // _this.$emit('input', _this.val);
      } else {
        if (
          Number(_this.listQuery.minCoin) >= Number(_this.listQuery.maxCoin)
        ) {
          _this.$message({
            type: 'warning',
            message: '区间最小值需要小于最大值!',
            onClose: function() {
              _this.listQuery.minCoin = '';
              _this.listQuery.maxCoin = '';
            }
          });
          return;
        }
        // _this.$emit('input', _this.val);
      }
    },
    dataFilter(val) {
      this.value = val;
      if (val) {
        // val存在
        this.options = this.optionsCopy.filter(item => {
          if (
            !!~item.agencyName.indexOf(val) ||
            !!~item.agencyName.toUpperCase().indexOf(val.toUpperCase())
          ) {
            return true;
          }
        });
      } else {
        // val为空时，还原数组
        this.options = this.optionsCopy;
      }
    },
    async getListAcc(listQuery) {
      this.listLoading = true;
      const res = await getListAcc(this.listQuery);
      if (res.data.code === 200) {
        this.tableData = res.data.data.records;
        this.total = res.data.data.total;
        this.listLoading = false;
        this.filterLoading = false;
      } else {
        this.listLoading = false;
        this.filterLoading = false;
      }
    },
    async getlistDetail() {
      this.detailLoading = true;
      const res = await getlistDetail(this.listQuery1);
      if (res.data.code === 200) {
        this.listDetail = res.data.data.records;
        this.detailTotal = res.data.data.total;
        this.detailLoading = false;
      } else {
        this.detailLoading = false;
      }
    },
    async getListDetailTotal() {
      this.detailLoading = true;
      const res = await getListDetailTotal(this.listQuery2);
      if (res.data.code === 200) {
        this.listDetailTotal = res.data.data.coinTotal;
        this.detailLoading = false;
      } else {
        this.detailLoading = false;
      }
    },
    async getAgency() {
      const res = await getAgency();
      res.data.data.forEach(element => {
        if (element.agencyName !== null) {
          this.optionsCopy.push(element);
          this.options.push(element);
        }
      });
    },
    timestampToTime(timestamp) {
      var date = new Date(timestamp);
      var Y = date.getFullYear() + '-';
      var M =
        (date.getMonth() + 1 < 10
          ? '0' + (date.getMonth() + 1)
          : date.getMonth() + 1) + '-';
      var D =
        (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
      var h =
        (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
      var m =
        (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) +
        ':';
      var s =
        date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
      return Y + M + D + h + m + s;
    },

    async handleView(row) {
      this.viewProtocolialog = true;
      this.listDetailTotal = 0;
      this.listQuery1.agencyId = row.agencyId;
      this.listQuery2.agencyId = row.agencyId;
      this.listQuery1.type = row.accType;
      this.listQuery2.type = row.accType;
      this.times = [
        this.timestampToTime(this.timeNow[0]),
        this.timestampToTime(this.timeNow[1])
      ];
      this.listQuery1.endTime = this.times[1];
      this.listQuery1.startTime = this.times[0];
      this.listQuery2.endTime = this.times[1];
      this.listQuery2.startTime = this.times[0];
      this.getlistDetail(this.listQuery1);
      this.getListDetailTotal(this.listQuery2);
    },

    // 搜索
    handleFilter() {
      this.filterLoading = true;
      this.listQuery.current = 1;
      this.getListAcc(this.listQuery);
      //   if (!this.listQuery.agencyId) {
      //     this.getListAcc(this.listQuery);
      //   } else {
      //     this.options.forEach(element => {
      //       if (element.agencyId === this.listQuery.agencyId) {
      //         this.listQuery.agencyName = element.agencyName;
      //         this.getListAcc(this.listQuery);
      //       }
      //     });
      //   }
    },
    // 明细搜索
    handleFilterDedail() {
      this.listQuery1.current = 1;
      if (this.times) {
        this.listQuery1.endTime = this.times[1];
        this.listQuery1.startTime = this.times[0];
        this.listQuery2.endTime = this.times[1];
        this.listQuery2.startTime = this.times[0];
      } else {
        this.listQuery1.endTime = '';
        this.listQuery1.startTime = '';
        this.listQuery2.endTime = '';
        this.listQuery2.startTime = '';
      }
      this.getlistDetail(this.listQuery1);
      this.getListDetailTotal(this.listQuery2);
    },
    // 调账
    async handleEdit(row, statetype) {
      this.dialogFormVisible = true;
      this.reconciliation = {
        id: row.id,
        coin: '',
        symbol: '',
        remark: ''
      };
    },
    // 曝光消耗
    auditCount() {
      this.btnLoading = true;
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          updateCount(this.reconciliation).then(res => {
            if (res.data.code === 200) {
              if (res.data.data) {
                this.$notify({
                  title: 'Success',
                  message: '调账成功',
                  type: 'success',
                  duration: 2000
                });
              } else {
                this.$notify({
                  title: '错误',
                  message: '调账失败',
                  type: 'fail',
                  duration: 2000
                });
              }
              this.dialogFormVisible = false;
              this.btnLoading = false;
            } else {
              this.btnLoading = false;
              this.$notify({
                title: '错误',
                message: res.data.msg,
                type: 'fail',
                duration: 2000
              });
            }
            this.getListAcc();
          });
        }
      });
    },
    // 查询备注详情
    queryDetail(agencyId) {
      this.exposureRemarkDetail = [];
      this.remarkDetailPage.current = 1;
      this.detailDialogVisible = true;
      this.remarkDetailPage.agencyId = agencyId;
      this.exposureRemarkTotal = 0;
      if (this.exposureRemarkDetail.length === 0) {
        this.loading = true;
      }
      getDetailByAgencyId(this.remarkDetailPage)
        .then(r => {
          this.exposureRemarkDetail = r.data.data.records;
          this.exposureRemarkTotal = r.data.data.total;
          this.loading = false;
        })
        .catch(error => {
          console.error(error);
        });
    },
    // 查询备注的分页
    handleSizeChange(num) {
      this.remarkDetailPage.size = num;
      this.queryDetail(this.remarkDetailPage.agencyId);
    },
    // 查询备注详情的页码变化
    handleCurrentChange(num) {
      this.remarkDetailPage.current = num;
      this.queryDetail(this.remarkDetailPage.agencyId);
    },
    // 新增备注
    handleRemark(data) {
      console.log(data);
      this.exposureRemarkDTO.agencyId = data.agencyId;
      this.exposureRemarkDTO.agencyName = data.agencyName;
      this.$prompt('新增备注', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
        .then(({ value }) => {
          this.exposureRemarkDTO.message = value;
          addDetailRemark(this.exposureRemarkDTO).then(r => {
            this.$message({
              type: 'success',
              message: data.agencyName + '新增备注成功'
            });
          });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '取消输入'
          });
        });
    },
    // 处理系统管理员和非系统管理员的颜色变换关系
    tableRowClassName({ row, rowIndex }) {
      console.log(row);
      if (row.operator === '系统管理员') {
        return 'warning-row';
      } else {
        return ' ';
      }
    }
  }
};
</script>
<style scoped>
.ec-input-range {
  display: inline-block;
  vertical-align: middle;
  margin-bottom: 10px;
}
.ec-input-range-divider {
  display: inline-block;
  width: 7px;
  height: 1px;
  background: #c0c4cc;
  margin-bottom: 4px;
}
.listDetailTotal {
  padding: 10px;
  font-size: 18px;
}
</style>
<style>
.el-table .warning-row {
  background: rgb(219, 229, 250);
}

.el-table .success-row {
  background: #f0f9eb;
}
</style>
<style>
.el-table .warning-row {
  background: rgb(219, 229, 250);
}

.el-table .success-row {
  background: #f0f9eb;
}
</style>
